<?php


namespace app\miniapp\controller\v3;


use app\common\cachemodel\FortuneCache;
use app\common\cachemodel\Goods;
use app\common\cachemodel\MonthFortune;
use app\common\cachemodel\SystemConfig;
use app\common\lib\astrolog\FortunesChange;
use app\common\lib\exception\ApiException;
use app\common\model\AppLogicVersion;
use app\common\model\Orders;
use app\common\model\Recode;
use app\common\model\SystemLogicVersion;
use app\miniapp\controller\v1\Auth;
use app\miniapp\model\MiniVersion;
use think\Log;
use function app\miniapp\isShowDownloadBar;
use function app\miniapp\miniFortuneMonthConfig;

class Fortune extends Auth
{
    protected $msg;

    /**
     *  运势介绍下单
     * @throws \Exception
     */
    public function fortuneIndex()
    {
        $rid = input('param.rid/s', '');
        $year = input('param.year/d', 0);
        $month = input('param.month/d', 0);

        if ($this->miniInfo && !$rid)
        {
            throw new ApiException('服务异常，档案缺失', 200, 406);
        }

        if ($this->user)
        { // 如果用户登陆了则进行参数校验
            $this->check_param($rid, $year, $month);
        }
        if ($this->msg)
        {
            Log::write('v7月运详情请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }

        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        //日历显示时间范围
        $range_start = config('fortune.fortune_time_range')['month']['start'];
        $range_end = config('fortune.fortune_time_range')['month']['end'];


        $OrdersModel = new  Orders();

        //解锁状态
        $unlock_status = 0;

        $MiniVersion = new MiniVersion();
        $map = [
            'version_id' => $this->headers['version'],
            'mini_type' => 'WEAPP',
            'app_type' => 1,
            'status' => 1
        ];
        $version_info = [];
        try
        {
            $version_info['weapp_btn_desc'] = $MiniVersion->getMiniAppBtnInfo($map, ['weapp_btn_desc']);
        }
        catch (\Exception $e)
        {

        }
        //如果是微信小程序，ios客户端则默认值为4，禁止购买
        if (($this->headers['app-type'] === 'WEAPP') && ((isset($this->headers['os'])) && $this->headers['os'] === 'ios') && !empty($version_info['weapp_btn_desc']))
        {
            if ('1.0.2' == $this->headers['version'])
            {
                $unlock_status = 0;
            } else
            {
                $unlock_status = 4;
            }
        }
        if ($this->headers['app-type'] === 'TT')
        {
            $goodType = 12;
            $gid = 53;
            $demoUrl = '/mini/astrolabe/fortune_month/sim_demo.png'; // 精简版示例图片
        } else
        {
            $goodType = 3;
            $gid = 20;
            $demoUrl = '/mini/astrolabe/fortune_month/demo2.png?v=123457'; // 完整版月运示例图片
        }

        if ($this->user)
        {//用户已经登录，那么查询订单
            $unlock_data = FortuneCache::getUnlockFortune($this->user['id'], $rid, $goodType);
            switch (true)
            {
                case in_array($now_time, $unlock_data['computing_fortune']):
                    $unlock_status = 1;
                    break;
                case in_array($now_time, $unlock_data['completed_fortune']):
                    $unlock_status = 2;
                    break;
            }
        }

        //统计订单人数
        $fortune_base_num = $OrdersModel->getSimFortuneOrderNum();

        $goods = (new Goods())->GoodsTypeInfo($goodType);
        $price = 19.00;
        foreach ($goods as $good)
        {
            if ($good['id'] == $gid)
            {
                $price = $good['now_prize'];
            }
        }
        $monthData = [];
        if ($unlock_status === 0)
        {   // 未解锁
            $monthData = [
                'title' => '解锁当前运势我能得到：',
                'content' => '',
                'list' => ['预知本月未来发展', '提前7天得到预警', '对应的方法与建议'],
                'price' => $price,
                'gid' => $gid
            ];
        } elseif ($unlock_status === 1)
        {   // 计算中
            $monthData = [
                'title' => '月度运势报告计算等待中：',
                'content' => "由于月运计算量较大、准了将在24小时内为您献上您所需要的月运解读\r\n\r\n请耐心等待哦～",
                'list' => [],
                'price' => $price,
                'gid' => $gid
            ];
        } elseif ($unlock_status === 2)
        {   // 计算完成
            $monthData = [
                'title' => '解锁当前运势我能得到：',
                'content' => '',
                'list' => ['预知本月未来发展', '提前7天得到预警', '对应的方法与建议'],
                'price' => $price,
                'gid' => $gid
            ];
        } elseif ($unlock_status === 4)
        {
            // 未解锁
            $monthData = [
                'title' => '解锁当前运势我能得到：',
                'content' => '',
                'list' => ['预知本月未来发展', '提前7天得到预警', '对应的方法与建议'],
                'price' => $price,
                'gid' => $gid
            ];
        }
        $hasPayOrder = $this->user ? (new \app\miniapp\common\Order())->getRecodeHasOrderPay((int)$this->user['id'], (int)$rid) : false;

        $mini_fortune_month_config = (new SystemConfig())->getSystemConfig(['mini_fortune_month_config']);

        $mini_fortune_month_config = isset($mini_fortune_month_config['mini_fortune_month_config']) ? $mini_fortune_month_config['mini_fortune_month_config'] : $mini_fortune_month_config;

        $resData = [
            'title' => '解锁你的精准月度运势报告',
            'unlock_num' => $fortune_base_num,
            'time_range' => [
                'start_time' => $range_start,
                'end_time' => $range_end
            ],
            'unlock_status' => $unlock_status,
            'demo' => [
                'title' => '月运示例',
                'url' => '/mini/astrolabe/fortune_month/demo.png?v=74771555',
                'url2' => $demoUrl,
                'img_bottom' => '/mini/astrolabe/fortune_month/bottom_img2.png'
            ],
            'month' => $monthData,
            'is_show_contact' => $hasPayOrder ? 1 : 0,
            'mini_fortune_month_config' => miniFortuneMonthConfig($mini_fortune_month_config),
            'is_show_download_bar' => isShowDownloadBar(isset($this->headers['channel']) && $this->headers['channel'] !== '' ? $this->headers['channel'] : 1)
        ];

        if ($this->headers['app-type'] === 'TT')
        {
            $resData['tt_share_data'] = config('miniapp_tt_share.fortune_index');
        }
        return show(config('code.success'), '请求成功', $resData);
    }

//    /**
//     * 获取运势下单信息
//     */
//    public function getFortuneOrderInfo()
//    {
//        $rid = input('param.rid/d', 0);
//        $year = input('param.year/d', 0);
//        $month = input('param.month/d', 0);
//        $this->check_param($rid, $year, $month);
//        if ($this->msg)
//        {
//            Log::write('v7月运详情请求参数有误：' . $this->msg, 'notice', true);
//            return show(config('code.error'), $this->msg);
//        }
//        //当前查看的时间
//        $now_time = strtotime($year . '-' . $month);
//        //解锁状态
//        $unlock_status = 0;
//
//        $unlock_data = FortuneCache::getUnlockFortune($this->user['id'], $rid, 3);
//        switch (true)
//        {
//            case in_array($now_time, $unlock_data['computing_fortune']):
//                $unlock_status = 1;
//                break;
//            case in_array($now_time, $unlock_data['completed_fortune']):
//                $unlock_status = 2;
//                break;
//        }
//
//        $goods = (new Goods())->GoodsTypeInfo(3);
//        $price = 19.00;
//        foreach ($goods as $good)
//        {
//            if ($good['id'] == 20)
//            {
//                $price = $good['now_prize'];
//            }
//        }
//        $resData = [
//            'gid' => 20,
//            'price' => $price,
//            'unlock_status' => $unlock_status,
//        ];
//
//        if ($this->headers['app-type'] === 'WEAPP')
//        {
//            $resData['pay_mode_list'] = [
//                [
//                    'id' => 2,
//                    'name' => '微信支付',
//                    'icon' => '/mini/astrolabe/order/wechat.png',
//                    'is_selected' => 1,
//                ]
//            ];
//        } else
//        {
//            $resData['pay_mode_list'] = [
//                [
//                    'id' => 2,
//                    'name' => '微信支付',
//                    'icon' => '/mini/astrolabe/order/wechat.png',
//                    'is_selected' => 1,
//                ], [
//                    'id' => 1,
//                    'name' => '支付宝支付',
//                    'icon' => '/mini/astrolabe/order/alipay.png',
//                    'is_selected' => 0,
//                ]
//            ];
//        }
//
//        return show(config('code.success'), '请求成功', $resData);
//    }

    /**
     * 月运详情
     * @throws \Exception
     */
    public function fortuneDetail()
    {
        $rid = input('param.rid/d', 0);
        $year = input('param.year/d', 0);
        $month = input('param.month/d', 0);
        $this->check_param($rid, $year, $month);
        if ($this->msg)
        {
            Log::write('v7月运详情请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }
        //当前查看的时间
        $now_time = strtotime($year . '-' . $month);
        $fortuneType = $this->headers['app-type'] === 'TT' ? 12 : 3;
        $isSimpleness = $fortuneType === 3 ? 0 : 1;
        // 获取已解锁的时间范围
        $unlockMonths = (new MonthFortune())->getReocdeFortuneUnlockMonths($rid,$isSimpleness);
        $time_range = array_map(function ($timeValue)
        {
            return date('Y-n', strtotime($timeValue));
        }, $unlockMonths);

        $goodType = $this->headers['app-type'] === 'TT' ? 13 : 7;
        $goodsContent = \app\miniapp\common\NatalReport::getGoods((int)$this->user['id'], $rid, $goodType, 0);
        if (in_array(date('Y-n', $now_time), $time_range, true))
        {   // 已下单解锁
            $map = ['uid' => (int)$this->user['id'], 'id' => $rid];
            //获取档案信息
            $recode_info = (new Recode())->getRecode($map);

            //获取运势信息
            $fortuneDetail = (new FortunesChange())->init2($recode_info, $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT), 'month', '', $isSimpleness);

            $unlock_status = (int)$fortuneDetail['status'];

            //用户计算成功后获取运势信息并查询逻辑版本信息
            if ($unlock_status === 2)
            {
                $fortune['underway_fortune'] = $this->resetFortuneTimeRange(1, $fortuneDetail['fortune']['underway_fortune']);
                $fortune['predicted_fortune'] = $this->resetFortuneTimeRange(2, $fortuneDetail['fortune']['predicted_fortune']);
                $fortune['completed_fortune'] = $this->resetFortuneTimeRange(3, $fortuneDetail['fortune']['completed_fortune']);
            } else
            {
                return show(config('code.error'), '该月运还在计算中，请稍后再试');
            }


            $fortune['goods_content'] = $goodsContent;
            $fortune['hint'] = '— 本小程序仅供娱乐 —';
            $fortune['is_show_download_bar'] = isShowDownloadBar($this->headers['channel']);
            if ($this->headers['app-type'] === 'TT')
            {
                $fortune['tt_share_data'] = config('miniapp_tt_share.fortune_info');

                //是否展示hint
                $MiniVersion = new MiniVersion();
                $map = [
                    'version_id' => $this->headers['version'],
                    'mini_type' => 'TT',
                    'app_type' => 1,
                    'status' => 1
                ];
                try
                {
//                        $tt_hint = $MiniVersion->where($map)->value('tt_hint');
                    $tt_hint = $MiniVersion->getMiniAppTtHintInfo($map);
                }
                catch (\Exception $e)
                {
                    $tt_hint['tt_hint'] = '— 本小程序仅供娱乐 —';
                }

                if ($tt_hint)
                {
                    $fortune['hint'] = $tt_hint['tt_hint'];
                } else
                {
                    $fortune['hint'] = '';
                }
            }
            return show(config('code.success'), '请求成功', $fortune);
        } else
        {
            return show(config('code.error'), '该月运未解锁');
        }
    }


    /**
     * 运势时间段处理
     * @param $type
     * @param $fortune
     * @return mixed
     */
    private function resetFortuneTimeRange($type, $fortune)
    {
        foreach ($fortune as $key => $item)
        {
            $start_time = implode('.', array_slice(explode('.', $item['start_time']), 1));
            $end_time = implode('.', array_slice(explode('.', $item['end_time']), 1));
            if ($item['end_days'])
            {
                //预警
                if ($type == 2)
                {
                    $fortune[$key]['time_range_des'] = '将持续' . $item['end_days'] . '天';

                } //进行中
                else
                {
                    $fortune[$key]['time_range_des'] = $item['end_days'] . '天后结束';
                }
            } else
            {
                $fortune[$key]['time_range_des'] = '已结束';
            }
            $fortune[$key]['time_range'] = $start_time . '-' . $end_time;
        }
        return $fortune;
    }

    /**
     * 检测运势首页请求参数
     * @param $rid
     * @param $year
     * @param $month
     * @return string
     */
    private function check_param($rid, $year, $month)
    {
        $this->msg = '';
        if (!$rid)
        {
            return $this->msg = '缺少档案';
        }
        if (!$year || !$month)
        {
            return $this->msg = '未知的时间';
        }
        if (!in_array($month, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
        {
            return $this->msg = '缺少月份';
        }
    }
}
